import {
  Tabs,
  Image,
  Button,
  List,
  Loading,
  Toast,
  PullRefresh,
  Navbar,
} from "@taroify/core";
import { View } from "@tarojs/components";
import { useEffect, useRef, useState } from "react";
import { abortRequest, requestPOST } from "@/request";
import Taro, { useShareAppMessage, useShareTimeline } from "@tarojs/taro";
import useSyncCallback from "@/hooks/useSyncCallback";
import { useSelector } from "react-redux";
import { RootState } from "@/store";

export default function Promotion() {
  const baseUrl = process.env.TARO_APP_API;
  const [value, setValue] = useState(1);
  const merchantInfo = useSelector(
    (state: RootState) => state.userInfo.merchantInfo
  );

  const [info, setInfo] = useState<any>({
    pageNumIndex: 1,
    total: 0,
    loading: true,
    hasMore: true,
    list: [],
  });
  const refreshingRef = useRef(false);
  const [reachTop, setReachTop] = useState(true);
  const userInfo = useSelector((state: RootState) => state.userInfo);
  const promotionId = useRef("");
  const useEffectO = useRef(false);

  const getPromotionListByParam = useSyncCallback(() => {
    requestPOST("merchants/getPromotionListByParam", {
      isPage: 1,
      pageNumIndex: info.pageNumIndex,
      pageSizeIndex: 10,
      promotionType: value,
    }).then((res: any) => {
      const { total, vos } = res;
      const list = [...info.list, ...vos];
      if (list.length >= total) {
        setInfo({
          ...info,
          total: total,
          list: [...list],
          hasMore: false,
          loading: false,
        });
      } else {
        setInfo({
          ...info,
          total: total,
          list: [...list],
          hasMore: true,
          loading: false,
        });
      }
      refreshingRef.current = false;
    });
  });
  const getPromotionListByParam1 = useSyncCallback(() => {
    requestPOST("merchants/getPromotionListByParam", {
      isPage: 1,
      pageNumIndex: info.pageNumIndex,
      pageSizeIndex: 10,
      promotionType: value,
    }).then((res: any) => {
      const { total, vos } = res;
      const list = [...info.list, ...vos];
      if (list.length >= total) {
        setInfo({
          ...info,
          total: total,
          list: [...list],
          hasMore: false,
          loading: false,
        });
      } else {
        setInfo({
          ...info,
          total: total,
          list: [...list],
          hasMore: true,
          loading: false,
        });
      }
      refreshingRef.current = false;
      useEffectO.current = false;
    });
  });

  const onLoad = () => {
    if (useEffectO.current) return;
    setInfo({ ...info, loading: true, pageNumIndex: info.pageNumIndex + 1 });
    getPromotionListByParam();
  };

  const handleChangeValue = (item) => {
    if (info.loading) {
      abortRequest();
    }

    setValue(item);
    setInfo({
      pageNumIndex: 1,
      total: 0,
      loading: true,
      hasMore: true,
      list: [],
    });
    getPromotionListByParam();
  };

  const clipboard = (data) => {
    Taro.setClipboardData({
      data,
      success() {
        // Toast.open({ type: "success", message: "复制成功" });
      },
    });
  };

  const saveImage = (images) => {
    const imgArr = images
      .split(",")
      .map((item) => saveImageFun(baseUrl + item));

    Taro.showLoading({
      title: "保存中...",
    });
    Promise.all([...imgArr])
      .then((res) => {
        console.log(res);
        Toast.open({ type: "success", message: "保存成功" });
      })
      .finally(() => {
        Taro.hideLoading();
      });
  };

  const saveImageFun = (url) => {
    return new Promise((resolve, reject) => {
      Taro.downloadFile({
        url: url,
        success: (res) => {
          if (res.statusCode === 200 && res.tempFilePath) {
            let img = res.tempFilePath;
            savePoster(img)
              .then((res) => {
                resolve(res);
              })
              .catch((res) => {
                reject(res);
              });
          } else {
            reject(res);
            Toast.open({
              message: "海报保存失败",
              icon: "error",
            });
          }
        },
        fail: () => {
          reject();
          Toast.open({
            message: "海报保存失败",
            icon: "error",
          });
        },
      });
    });
  };

  const savePoster = (url) => {
    return new Promise((resolve, reject) => {
      Taro.saveImageToPhotosAlbum({
        filePath: url,
        success: (res) => {
          resolve(res);
        },
        fail: (res) => {
          reject(res);
          Toast.open({
            message: "海报保存失败",
            icon: "error",
          });
        },
      });
    });
  };

  const onRefresh = () => {
    refreshingRef.current = true;
    setInfo({
      pageNumIndex: 1,
      total: 0,
      loading: true,
      hasMore: true,
      list: [],
    });
    getPromotionListByParam();
  };

  const previewImage = (images, index) => {
    Taro.previewImage({
      current: index,
      urls: images.split(",").map((item) => baseUrl + item),
    });
  };
  console.log(userInfo);

  useShareAppMessage((res) => {
    return {
      title:
        "每日推广：" +
        info.list.find((item) => item.id === promotionId.current)
          .promotionTitle, // 转发后 所显示的title
      path: `packages/promotionDetail/index?id=${promotionId.current}&userId=${userInfo.userId}`, // 相对的路径
      imageUrl:
        baseUrl +
        info.list
          .find((item) => item.id === promotionId.current)
          .promotionImage.split(",")[0],
    };
  });

  useEffect(() => {
    useEffectO.current = true;
    getPromotionListByParam1();
  }, []);

  return (
    <View className="taroContainer" style={{ overflow: "hidden" }}>
      <Navbar
        fixed
        nativeSafeTop
        safeArea="top"
        className="navBar"
        style={{ background: "#e3f3fe" }}
        placeholder={true}
      >
        <Navbar.Title style={{ maxWidth: "100%" }}>
          <View
            style={{
              display: "flex",
              alignItems: "center",
              width: "100vw",
              justifyContent: "center",
              position: "relative",
              fontSize: "28rpx",
              fontWeight: "normal",
            }}
          >
            <View style={{ position: "absolute", left: 20 }}>
              {merchantInfo.merchantName}
            </View>
            <View>每日推广</View>
          </View>
        </Navbar.Title>
      </Navbar>
      <Tabs value={value} onChange={handleChangeValue}>
        <Tabs.TabPane value={1} title="每日必推"></Tabs.TabPane>
        <Tabs.TabPane value={2} title="国补专区"></Tabs.TabPane>
        <Tabs.TabPane value={3} title="抢单备货"></Tabs.TabPane>
      </Tabs>
      <PullRefresh
        loading={refreshingRef.current}
        reachTop={reachTop}
        onRefresh={onRefresh}
        style={{ height: "100%" }}
      >
        <List
          loading={info.loading}
          hasMore={info.hasMore}
          onLoad={onLoad}
          fixedHeight
          style={{
            height: "calc(100% - 45px)",
          }}
        >
          <View
            style={{
              display: "flex",
              flexDirection: "column",
              gap: "20rpx",
              padding: "24rpx",
              boxSizing: "border-box",
            }}
          >
            {info.list.map((item) => (
              <View
                key={item.id}
                style={{
                  padding: "30rpx",
                  backgroundColor: "#fff",
                  borderRadius: "14rpx",
                }}
              >
                <View
                  style={{
                    display: "flex",
                    alignItems: "center",
                    gap: "20rpx",
                  }}
                  onClick={() =>
                    Taro.navigateTo({
                      url: `/packages/promotionDetail/index?id=${item.id}&detail=1`,
                    })
                  }
                >
                  <View style={{ flex: "0 0 76rpx" }}>
                    <Image
                      src={baseUrl + item.promotionLogo}
                      width={76}
                      height={76}
                      style={{ borderRadius: "50%" }}
                    />
                  </View>
                  <View
                    style={{
                      fontWeight: "bold",
                      fontSize: "29rpx",
                      color: "#333333",
                    }}
                  >
                    {item.promotionTitle}
                  </View>
                </View>
                <View
                  style={{
                    fontSize: "26rpx",
                    color: "#333333",
                    marginTop: "30rpx",
                  }}
                  onClick={() =>
                    Taro.navigateTo({
                      url: `/packages/promotionDetail/index?id=${item.id}&detail=1`,
                    })
                  }
                >
                  {item.promotionContent}
                </View>
                <View
                  style={{
                    marginTop: "30rpx",
                    display: "flex",
                    flexWrap: "wrap",
                    gap: "20rpx",
                  }}
                >
                  {item.promotionImage.split(",").map((img, index) => (
                    <Image
                      key={index}
                      src={baseUrl + img}
                      width={143}
                      height={215}
                      mode="widthFix"
                      onClick={() => previewImage(item.promotionImage, index)}
                    />
                  ))}
                </View>
                <View
                  style={{
                    display: "flex",
                    alignItems: "center",
                    gap: "20rpx",
                    justifyContent: "flex-end",
                    marginTop: "27rpx",
                  }}
                  onClick={() => {
                    promotionId.current = item.id;
                  }}
                >
                  {/* <Button
                    disabled={!item.promotionImage}
                    variant="contained"
                    shape="round"
                    size="small"
                    onClick={() => saveImage(item.promotionImage)}
                  >
                    保存图片
                  </Button> */}
                  <Button
                    variant="contained"
                    shape="round"
                    size="small"
                    onClick={() => clipboard(item.promotionContent)}
                  >
                    复制文案
                  </Button>
                  <Button
                    variant="contained"
                    color="primary"
                    shape="round"
                    size="small"
                    openType="share"
                  >
                    {/* <ShareOutlined /> */}
                    {/* <Image src={ShareIcon} width={22} height={22} /> */}
                    <View>一键转发</View>
                  </Button>
                </View>
              </View>
            ))}
          </View>
          {!refreshingRef.current && (
            <List.Placeholder>
              {info.loading && <Loading>加载中...</Loading>}
              {!info.hasMore && "没有更多了"}
            </List.Placeholder>
          )}
        </List>
      </PullRefresh>
    </View>
  );
}
